package cmd

import (
	"gvm/classpath"
	"gvm/rtda"
	"gvm/rtda/heap"
	"strings"
)

type Cmd struct {
	HelpFlag         bool
	VersionFlag      bool
	VerboseClassFlag bool
	VerboseInstFlag  bool
	CpOption         string
	XjreOption       string
	Class            string
	Args             []string
}

func ParseCmd(args []string) *Cmd {
	cmd1 := &Cmd{}
	args = removeSpace(args)
	if len(args) == 1 {
		if "--help" == args[0] || "?" == args[0] {
			cmd1.HelpFlag = true
		}

		if "--version" == args[0] || "-v" == args[0] {
			cmd1.VersionFlag = true
		}
	}
	if len(args) > 1 {
		cmd1.Class = args[0]
		cmd1.Args = args[1:]
		for index, value := range cmd1.Args {
			if value == "--classpath" || value == "--cp" {
				if len(cmd1.Args) > index+1 {
					cmd1.CpOption = cmd1.Args[index+1]
				}
			} else if value == "--xjre" {
				if len(cmd1.Args) > index+1 {
					cmd1.XjreOption = cmd1.Args[index+1]
				}
			}
		}
	}
	cmd1.VerboseClassFlag = true
	cmd1.VerboseInstFlag = true
	return cmd1
}

func removeSpace(args []string) []string {
	var arr []string
	for _, v := range args {
		is := strings.TrimSpace(v)
		if len(is) > 0 {
			arr = append(arr, is)
		}
	}
	return arr
}

// 创建JVM
func NewJVM(command *Cmd) *JVM {
	// 构建classpath 对象     封装参数并且这些对象可以根据参数读取对应的class的二进制数据
	classPath := classpath.Parse(command.XjreOption, command.CpOption)

	// 构建classloader对象    用于加载class   class 二进制数据 -> class file 解析  -> class元数据+jclass对象
	classloader := heap.NewClassLoader(classPath)

	// 返回JVM

	//className := strings.Replace(command.Class, ".", "/", -1)
	//classloader.LoadClass(className)

	return &JVM{cmd: command, classLoader: classloader, mainThread: rtda.NewJThread()}

}
